package com.my.screenadapter.shell;

/**
 * Created by Administrator on 2017/12/15.
 */

import android.nfc.Tag;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class ShellExec {
    private static final String TAG = "ShellExec";

    /**
     * 行shell命令函数
     */
    public static String do_exec(String cmd) {
        try {
            Process exeEcho = Runtime.getRuntime().exec("sh");
            DataOutputStream os = new DataOutputStream(exeEcho.getOutputStream());
            os.writeBytes(cmd);
            os.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cmd;
    }


    public static String execute(String cmd) throws IOException, InterruptedException {


        StringBuffer sb = new StringBuffer();

        final Process p = Runtime.getRuntime().exec(cmd);

        /*为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞*/
        Thread t = new Thread(new InputStreamRunnable(p.getErrorStream(), "ErrorStream"));
        t.start();

        BufferedReader reader = null;
        InputStream output = p.getInputStream();
        //InputStream error = p.getErrorStream();
        String line = "";

        reader = new BufferedReader(new InputStreamReader(output));
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        p.waitFor();
//      if (0x00 == sb.length()) {
//          reader = new BufferedReader(new InputStreamReader(error));
//
//          while ((line = reader.readLine())!= null) {
//              sb.append(line + "\n");
//          }
//      }
        reader.close();
        p.destroy();
        return sb.toString();
    }
}

/**
 * 读取InputStream的线程
 */
class InputStreamRunnable implements Runnable {
    private static final String TAG = "InputStreamRunnable";
    BufferedReader bReader = null;
    String type = null;

    public InputStreamRunnable(InputStream is, String _type) {
        try {
            bReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(is), "UTF-8"));
            type = _type;
        } catch (Exception ex) {
            Log.e(TAG,"EEEEEEEEEEEE");
            ex.printStackTrace();
        }
    }

    public void run() {
        String line;
        int lineNum = 0;

        try {
            while ((line = bReader.readLine()) != null) {
                lineNum++;
                //Thread.sleep(200);
            }
            bReader.close();
        } catch (Exception ex) {
            Log.e(TAG,"EXXXXXXXXXXX");
            ex.printStackTrace();
        }
    }
}
